package mm.test;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;

import org.apache.jasper.runtime.HttpJspBase;

import mm.util.LOG;

public class MockChainImpl extends MockChainAdapter implements MockChain {
	
	private List<Filter> filters;
	private int pointer;

	public MockChainImpl(List<Filter> filters) {
		this.filters=filters;
	}
	
	public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
		///MockRequest mockRequest=(MockRequest)req;
		MockResponse mockResponse=(MockResponse)response;
		HttpServletRequest req=(HttpServletRequest)request;
		HttpServletResponse res=(HttpServletResponse)response;
		if(filters==null||filters.isEmpty()||pointer>filters.size()-1){
			String path=((HttpServletRequest) request).getServletPath();
			LOG.debug("Rendering jsp: "+path);
			JspFactory.setDefaultFactory(new MockJspFactory());
			HttpJspBase jspPage = getJspClass(path);
			jspPage._jspInit();
			jspPage._jspService(req, res);
			response.getWriter().println(((MockResponse)res).getContent());
			return;
		}
		Filter currentFilter = filters.get(pointer++);
		mockResponse.getFilterTour().add(currentFilter.getClass().getName());
		currentFilter.doFilter(request, response, this);
	}

	private HttpJspBase getJspClass(String path) {
		HttpJspBase jsp=null;
		try {
			jsp = JspClassLoader.getInstance().loadJsp(path);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsp;
	}

}
